﻿using System.Transactions;
using AutoMapper;
using BaseData.Domain;
using BaseData.ErrorCode;
using BaseData.Infrastructrue.Interfaces;
using BaseData.WriteApi.Application.Command.Roles;
using BaseData.WriteApi.Application.CommandHandler.Users;
using MediatR;

namespace BaseData.WriteApi.Application.CommandHandler.Roles
{
    public class InsertRoleCommandHandler : IRequestHandler<InsertRoleCommand, Apiresult<int>>
    {
        private readonly IBasepository<UserInfo> userpository;  // 用户信息仓储接口
        private readonly IBasepository<Role> rolepository;  // 角色仓储接口
        private readonly IBasepository<UserRole> uRpository;  // 用户角色仓储接口
        private readonly IBasepository<Permission> permisspository;  // 权限仓储接口
        private readonly IBasepository<RolePermiss> rolePerpository;  // 角色权限仓储接口
        private readonly IMapper mapper;  // 对象映射器
        private readonly ILogger<InsertRoleCommandHandler> logger;  // 日志记录器

        /// <summary>
        /// 构造函数，注入所需的服务
        /// </summary>
        /// <param name="_userpository">用户信息仓储</param>
        /// <param name="_rolepository">角色仓储</param>
        /// <param name="_URpository">用户角色仓储</param>
        /// <param name="_permisspository">权限仓储</param>
        /// <param name="_rolePerpository">角色权限仓储</param>
        /// <param name="_mapper">对象映射器</param>
        /// <param name="_logger">日志记录器</param>
        public InsertRoleCommandHandler(
            IBasepository<UserInfo> _userpository,
            IBasepository<Role> _rolepository,
            IBasepository<UserRole> _URpository,
            IBasepository<Permission> _permisspository,
            IBasepository<RolePermiss> _rolePerpository,
            IMapper _mapper,
            ILogger<InsertRoleCommandHandler> _logger)
        {
            userpository = _userpository;
            rolepository = _rolepository;
            uRpository = _URpository;
            permisspository = _permisspository;
            rolePerpository = _rolePerpository;
            mapper = _mapper;
            logger = _logger;
        }
        public async Task<Apiresult<int>> Handle(InsertRoleCommand request, CancellationToken cancellationToken)
        {
            using(var tran= new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    Role role = new Role()
                    {
                        RoleName = request.RoleName,
                    };
                    var roleResult = await rolepository.InsertAsync(role);
                    if (roleResult <= 0)
                    {
                        tran.Dispose();
                        return new Apiresult<int>()
                        {
                            Code = ResultCode.添加失败,
                            Message = "角色信息插入失败"
                        };
                    }
                    var permiss = await permisspository.GetModel(x => x.PermissionId == request.PermissionId);
                    if (permiss == null)
                    {
                        tran.Dispose();
                        return new Apiresult<int>()
                        {
                            Code = ResultCode.查询失败,
                            Message = "权限信息不存在"
                        };
                    }
                    RolePermiss rolePermiss = new RolePermiss()
                    {
                        RoleId = role.RoleId,
                        PermissionId = request.PermissionId,
                    };
                    var rolepermissResult =await rolePerpository.InsertAsync(rolePermiss);
                    if (rolepermissResult <= 0)
                    {
                        tran.Dispose();
                        return new Apiresult<int>() { Code = ResultCode.添加失败, Message = "角色权限信息插入失败" };
                    }
                    tran.Complete();
                    return new Apiresult<int>()
                    {
                        Code = ResultCode.添加成功,
                        Message = "角色信息添加成功"
                    };
                }
                catch (Exception ex)
                {
                    tran.Dispose();
                    logger.LogError(ex, "InsertRoleCommandHandler Handle Error");
                    return new Apiresult<int>()
                    {
                        Code = ResultCode.添加失败,
                        Message = "角色信息插入异常"
                    };
                }
            }
        }
    }
}
